#!/usr/bin/env python
# -*- coding:utf-8 -*-
# えきから時刻表の列車別詳細時刻表からデータを抽出し、OuDia用のファイルを生成
#
# installing BeautifulSoup:
#        http://www.crummy.com/software/BeautifulSoup/
#        check python ver and get 3.0xxx or 3.1xxx, and python setup.py install
import codecs
import locale
import sys
from optparse import OptionParser
import EkikaraDb
import getTimetableLog
import OudiaCSV
import OudiaFormat


def main():
    CONSOLE_ENCODE = locale.getpreferredencoding()
    logger = getTimetableLog.logging.getLogger("setdiadatalog")
    # save command line
    CmdLine = []
    for cmd_item in sys.argv:
        CmdLine.append(cmd_item.decode(CONSOLE_ENCODE))
    # parse command line
    optParser = OptionParser(usage="%prog -d DBFILE -f FILENAME [options] ", version="%prog 0.4")
    optParser.add_option("-d", "--db-file", dest="dbFile", help="specify sqlite db file.", metavar="FILE")
    optParser.add_option("-f", "--output-file",
                         dest="outputFile",
                         help="export filename. less then stdout, add ext output format (default .oud)",
                         metavar="OUTFILE")
    optParser.add_option("-o", "--output-format",
                         dest="outputFormat",
                         default="oud",
                         #help="csv, oud or WinDia",
                         help="csv, oud",
                         metavar="TYPE")
    optParser.add_option("-s", "--status", action="store_true", dest="status", help="print status messages.")
    optParser.add_option("-t", "--timetable-id", dest="targetTimetableId", default=0,
                         help="target TIMETABLE-ID. default is 0. Listing timetable-id by infoTimetable.py -l",
                         metavar="TIMETABLE-ID")
    optParser.add_option("", "--station-list",
                         dest="stationList",
                         help="specify station list FIlE",
                         metavar="FILE")
    optParser.add_option("", "--station-list-encode",
                         dest="stationListEncode",
                         default="CP932",
                         help="file ENCODE for station list. default is CP932",
                         metavar="ENCODE")
    optParser.add_option("", "--no-check-order", action="store_false", dest="isCheckOrder", default=True,
                         help="no checking train stop time order. default checking order")
    (OPTIONS, args) = optParser.parse_args()
    # check cmdline params.
    if OPTIONS.dbFile:
        db = EkikaraDb.EkikaraDb(logger=logger, filename=OPTIONS.dbFile)
    else:
        optParser.error(u"missing -d DBFILE and -f OUTFILE")
        logger.info(u"missing -d DBFILE and -f OUTFILE")
        sys.exit(1)
    #--------- main
    target = EkikaraDb.Timetable(db=db,
                                 target_timetable_id=OPTIONS.targetTimetableId,
                                 logger=logger)
    if OPTIONS.outputFormat == "csv" or OPTIONS.outputFormat == "oud":
        if OPTIONS.outputFormat == "csv":
            # exporter is TimetableExporter object.
            exporter = OudiaCSV.OudiaCsv(db=db,
                                         timetable_id=target.getId(),
                                         logger=logger,
                                         argv=CmdLine,
                                         status_option=OPTIONS.status,
                                         console_encode=CONSOLE_ENCODE,
                                         )
        elif OPTIONS.outputFormat == "oud":
            exporter = OudiaFormat.OudiaFormat(db=db,
                                               timetable_id=target.getId(),
                                               logger=logger,
                                               argv=CmdLine,
                                               status_option=OPTIONS.status,
                                               console_encode=CONSOLE_ENCODE,
                                               isCheckOrder=OPTIONS.isCheckOrder,
                                               )
            if OPTIONS.stationList:
                exporter.setStationList(OPTIONS.stationList, OPTIONS.stationListEncode)
        if OPTIONS.outputFile:
            fout = codecs.open(OPTIONS.outputFile + "." + OPTIONS.outputFormat, "wb", exporter.encode)
            #for line in exporter.put() :
            #    fout.write(line+exporter.newline)
            exporter.put(fout)
            fout.close()
        else:
            sys.stdout = codecs.getwriter(exporter.encode)(sys.stdout)
            if sys.platform == "win32":
                import msvcrt
                import os
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)        # stdoutをbinmodeに(U*nix系は元々binmode)
            #for line in exporter.put() :
            #    sys.stdout.write(line+exporter.newline)
            exporter.put(sys.stdout)
        if OPTIONS.status:
            sys.stderr.write(u"done.\n".encode(CONSOLE_ENCODE))
    else:
        optParser.error(u"unknown output format type=[%s]" % (OPTIONS.outputFormat))
        logger.info(u"unknown output format type=[%s]\n" % (OPTIONS.outputFormat))
        sys.exit(1)


if __name__ == "__main__":
    main()
